﻿using System;
using System.Text.RegularExpressions;
using HashFoo.Core;

namespace HashFoo.MigratorFoo
{
    public class SimpleMigrationInverter : IMigrationInverter
    {
        private const string CreateTableRegex = @"create table \[([\w\d_]+)\]";
        private const string AlterTableRegex = @"alter table \[([\w\d_]+)\]";
        private const string AddConstraintRegex = @"add constraint ([\w\d_]+)";
        private const string AddColumnRegex = @"add (\w[\w\d_]+)";

        #region IMigrationInverter Members

        public string InvertCommand(string script)
        {
            if (Regex.IsMatch(script, CreateTableRegex))
            {
                return ParseCreateTable(script);
            }

            if (Regex.IsMatch(script, AlterTableRegex))
            {
                return ParseAlterTable(script);
            }

            return string.Empty;
        }

        #endregion

        #region Parsers
        private static string ParseCreateTable(string script)
        {
            var match = Regex.Match(script, CreateTableRegex);
            if (!match.Success)
            {
                throw new ArgumentException("No create table found in sql script");
            }

            return "drop table [{0}];{1}".DoFormat(match.Groups[1].Value, Environment.NewLine);
        }

        private static string ParseAlterTable(string script)
        {
            var alterTableMatch = Regex.Match(script, AlterTableRegex);
            var downScript = "alter table [{0}] ".DoFormat(alterTableMatch.Groups[1].Value);

            if (Regex.IsMatch(script, AddConstraintRegex))
            {
                var match = Regex.Match(script, AddConstraintRegex);
                return downScript + "drop constraint {0};{1}".DoFormat(match.Groups[1].Value, Environment.NewLine);
            }
            else if (Regex.IsMatch(script, AddColumnRegex))
            {
                var match = Regex.Match(script, AddColumnRegex);
                return downScript + "drop column {0};{1}".DoFormat(match.Groups[1].Value, Environment.NewLine);
            }

            return string.Empty;
        }
        #endregion
    }
}
